package com.pxx.service.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.item.common.PageResult;
import com.pxx.item.pojo.Sku;
import com.pxx.item.pojo.Stock;
import com.pxx.item.pojo.TbSpu;
import com.pxx.item.pojo.TbSpuDetail;
import com.pxx.item.pojo.vo.SpuVo;
import com.pxx.service.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;


    public PageResult<SpuVo> querySpuVoPage(String key, Boolean saleable, Integer page, Integer rows) {
        //搜索条件创建
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();

        //查询的条件
        if (!StringUtils.isEmpty(key)){
            criteria.andLike("title","%"+key+"%");
        }
        if(saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }

        //分页条件的设置
        PageHelper.startPage(page,rows);

        //执行查询
        List<TbSpu> tbSpus = spuMapper.selectByExample(example);
        PageInfo<TbSpu> tbSpuPageInfo = new PageInfo<>(tbSpus);

        //数据整理
        List<SpuVo> list =  new ArrayList<SpuVo>();

        tbSpus.forEach(spu ->{
            SpuVo spuVo = new SpuVo();
            //拷贝数据到spuvo集合中
            BeanUtils.copyProperties(spu,spuVo);
            //查询分类名称
            List<String> names =  categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));

            spuVo.setCname(StringUtils.join(names,"/"));
            //查询品牌的名称
            spuVo.setBname(brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());
            list.add(spuVo);
        });

        return new PageResult<SpuVo>(tbSpuPageInfo.getTotal(),list);
    }

    /**
     * 商品新增
     * @param spuVo
     *
     * Transactional : 当前方法中，保证事物的一致性
     * ACID
     * 持久性，一致性，隔离性，原子性
     */
    @Transactional
    public void saveGoods(SpuVo spuVo) {
        //插入spu的数据
        spuVo.setId(null);
        spuVo.setSaleable(true);
        spuVo.setValid(true);
        spuVo.setCreateTime(new Date());
        spuVo.setLastUpdateTime(new Date());
        spuMapper.insertSelective(spuVo);
        //插入spuDetail
        TbSpuDetail spuDetail = spuVo.getSpuDetail();
        spuDetail.setSpuId(spuVo.getId());
        spuDetailMapper.insertSelective(spuDetail);

        //新增sku的数据同时新增库存数据
        List<Sku> skus = spuVo.getSkus();
        //skus里面有数据，则循环
        if (!CollectionUtils.isEmpty(spuVo.getSkus())){
            saveSkuAndStock( spuVo) ;
        }
    }



    private void saveSkuAndStock(SpuVo spuVo){
        spuVo.getSkus().forEach(sku -> {
            //新增sku
            sku.setSpuId(spuVo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            skuMapper.insertSelective(sku);
            //新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stockMapper.insertSelective(stock);
        });

    }

    public TbSpuDetail querySpuDetailBySpuId(Long spuId) {

        return spuDetailMapper.selectByPrimaryKey(spuId);
    }

        public List<Sku> querySkuListBySpuId(Long spuId) {
            Sku sku = new Sku();
            sku.setSpuId(spuId);
            List<Sku> skuList = skuMapper.select(sku);
            //查询对应的库存数
            skuList.forEach(sku1 -> {
            Stock stock =  stockMapper.selectByPrimaryKey(sku1.getId());
                sku1.setStock(stock.getStock());
            });
            return skuList;
        }

    public void updateGoods(SpuVo spuVo) {

            //查询skus的集合
        List<Sku> skus = querySkuListBySpuId(spuVo.getId());
        if (!CollectionUtils.isEmpty(skus)){
            //            List<Long> skusId = skus.stream().map(sku -> sku.getId()).collect(Collectors.toList());
            List<Long> SkuIds = new ArrayList<>();
            for (Sku sku : skus) {
                SkuIds.add(sku.getId());
            }
            //删除以前的库存
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId",SkuIds);
            stockMapper.deleteByExample(example);
            //删除以前的SKU
            Sku sku = new Sku();
            sku.setSpuId(spuVo.getId());
            skuMapper.delete(sku);
        }
        //新增库存和sku
        saveSkuAndStock(spuVo);

        //修改spu和spu_detail的数据
        spuVo.setLastUpdateTime(new Date());
        spuVo.setCreateTime(null);//  因为我们使用的 updateSelective 会判断对象中的数据如果为空，那么为空的那个字段数据就不做更改，保持原来的，
        spuMapper.updateByPrimaryKeySelective(spuVo);

        //更新spuDetail的详情
        spuDetailMapper.updateByPrimaryKeySelective(spuVo.getSpuDetail());

    }
}
